package com.uchengwang.ui.cm_ui.login.LoginHttp;

import android.app.Activity;
import android.net.Uri;
import android.text.TextUtils;

import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.LoginConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.functions.http.listener.OnHttpResultSingleListener;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.cm_ui.cycle.bean.RyGroupBean;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.me.presenter.HttpMeManager;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

/**
 * Created by U城网 on 2017/7/14.
 */

public class LoginHttpManager {
    private static LoginHttpManager manager;
    private static List<UserBean> userList = new ArrayList<>();//加载好友信息到内存
    private static List<RyGroupBean> groupBeanList = new ArrayList<>();//加载与我相关群信息到内存

    private LoginHttpManager (){}

    public static LoginHttpManager getManager() {
        if (manager == null){
            manager = new LoginHttpManager();
        }
        return manager;
    }

    /**
     *登录成功 将自己的好友和关注更新到本地数据库
     */
    public void downloadMyFriends(final Activity activity){
        if (!UCommonUtil.getUtil().isLogin()){
            //没有登录 不请求
            return;
        }
        //获取关注的全部[个人和社团]
        HttpMeManager.getPresenter().getFriends(activity, UCommonUtil.getUtil().getId(), 1, 999, 2, 0, new HttpMeManager.UsersListener() {
            @Override
            public void result(int status, int count, List<UserBean> list) {
                LiteOrmDBUtil.getLiteOrm(activity).deleteAll(UserBean.class);

                if (list != null && list.size() >0){
                    LiteOrmDBUtil.getLiteOrm(activity).insertAll(list);
                }
                if (userList == null){
                    userList = new ArrayList<UserBean>();
                }
                if (list != null){
                    userList.addAll(list);
                }


                //获取好友的全部[个人和社团]
                HttpMeManager.getPresenter().getFriends(activity, UCommonUtil.getUtil().getId(), 1, 999, 3, 0, new HttpMeManager.UsersListener() {
                    @Override
                    public void result(int status, int count, List<UserBean> list) {
                        if (list != null && list.size() >0){
                            LiteOrmDBUtil.getLiteOrm(activity).insertAll(list);
                        }

                        if (list != null){
                            userList.addAll(list);
                        }
                    }
                });

            }
        });
    }

    public List<UserBean> getUserList(){
        return userList;
    }

    /**
     * 查看一个用户的信息
     * */
    public UserBean checkUserInfo(Activity context, String uid){
        if (TextUtils.isEmpty(uid)){
            return null;
        }
        if (userList == null){
            userList = LiteOrmDBUtil.getLiteOrm(context).getQueryAll(UserBean.class);
        }
        for (UserBean bean : userList){
            if (uid.equals(String.valueOf(bean.getId()))){
                return bean;
            }
        }

        try {
            Long.parseLong(uid);
        }catch (NumberFormatException e){
            return null;
        }
        //本地数据库没有  从网上获取用户信息
        HttpMeManager.getPresenter().getUserInfo(context, Long.parseLong(uid), new OnHttpResultSingleListener<UserBean>() {
            @Override
            public void onResult(int status, String msg, UserBean bean) {
                if (bean != null){
                    String name = !TextUtils.isEmpty(bean.getRemarkName()) ? bean.getRemarkName() : bean.getNickName();

                    String headUrl = "";
                    if (TextUtils.isEmpty(bean.getUserAvatar())){
                        headUrl = "http://ucw-user.oss-cn-shanghai.aliyuncs.com/default_image.jpg";
                    }else {
                        headUrl = bean.getUserAvatar();
                    }
                    UserInfo info = new UserInfo(String.valueOf(bean.getId()), name, Uri.parse(headUrl));
                    RongIM.getInstance().refreshUserInfoCache(info);
                }
            }
        });

        return null;
    }

    /**
     * 查看一个群组的信息
     * */
    public RyGroupBean checkGroupInfo(Activity context, final String groupId){
        if (groupBeanList == null){
            groupBeanList = LiteOrmDBUtil.getLiteOrm(context).getQueryAll(RyGroupBean.class);
        }
        for (RyGroupBean bean : groupBeanList){
            if (groupId.equals(String.valueOf(bean.getId()))){
                return bean;
            }
        }

        try {
            Long.parseLong(groupId);
        }catch (NumberFormatException e){
            return null;
        }

        RyGroupManager.getManager().getGroupInfo(context, Long.parseLong(groupId), new OnHttpResultSingleListener<RyGroupBean>() {
            @Override
            public void onResult(int status, String msg, RyGroupBean ryGroupBean) {
                if (ryGroupBean != null){
                    Group group = new Group(groupId, ryGroupBean.getGroupName(), Uri.parse(ryGroupBean.getGroupLogo()));
                    RongIM.getInstance().refreshGroupInfoCache(group);
                }
            }
        });

        return null;
    }

    /**
     * 登录成功 将自己的群组全部存在本地
     * */
    public void downloadMyGroups(final Activity activity){
        if (!UCommonUtil.getUtil().isLogin()){
            //没有登录 不请求
            return;
        }

        RyGroupManager.getManager().getMyGroups(activity, 1, 999, 0, new OnHttpResultListener<RyGroupBean>() {
            @Override
            public void onResult(int status, String msg, int total, List<RyGroupBean> list) {
                if (list != null && list.size() >0){
                    LiteOrmDBUtil.getLiteOrm(activity).deleteAll(RyGroupBean.class);
                   LiteOrmDBUtil.getLiteOrm(activity).insertAll(list);
                }
                if (groupBeanList == null){
                    groupBeanList = new ArrayList<RyGroupBean>();
                }
                if (list != null){
                    groupBeanList.addAll(list);
                }
            }
        });
    }

    /**
     * 登录(含三方)
     * */
    public void login(final Activity activity, MapRequest map, final OnResultListener listener){
        HttpManager.newInstance(activity).query(LoginConfig.Login.method, LoginConfig.Login.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(activity, msg);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                LoadingUtils.getUtils().hide();
                if (status == 0){
                    //登录成功
                    UserBean userBean = JsonUtils.getManager().stringToBean(data, UserBean.class);
                    UChengApplication.TOKEN = userBean.getToken();
                    UChengApplication.nickName = userBean.getNickName();
                    UChengApplication.uniId = userBean.getUniId();
                    UChengApplication.myUniId = userBean.getUniId();
                    UChengApplication.schoolName = userBean.getUniName();
                    UChengApplication.mySchoolName = userBean.getUniName();
                    UChengApplication.uniDataId = userBean.getUniDataId();
                    UChengApplication.sex = userBean.getSex();

                    UChengApplication.userAvatar = userBean.getUserAvatar();
                    UChengApplication.userRole = userBean.getUserRole();
                    UChengApplication.isAuthen = userBean.isAuth();

                    if (UChengApplication.userRole == BaseConfig.CLUB_ROLE){
                        UChengApplication.clubId = userBean.getId();
                    }else {
                        UChengApplication.uid = userBean.getId();
                    }

                    SPUtils.getPreferences(activity).putInt(BaseConfig.SEX, userBean.getSex());
                    SPUtils.getPreferences(activity).putInt(BaseConfig.USER_ROLE, userBean.getUserRole());
                    SPUtils.getPreferences(activity).setAccountId(userBean.getId());
                    SPUtils.getPreferences(activity).setAccountPw(userBean.getUserPwd());
                    SPUtils.getPreferences(activity).setUserName(userBean.getUserName());
                    SPUtils.getPreferences(activity).setRealName(userBean.getRealName());
                    SPUtils.getPreferences(activity).putString(BaseConfig.NICK_NAME, userBean.getNickName());
                    SPUtils.getPreferences(activity).putString(BaseConfig.USER_AVATAR, userBean.getUserAvatar());
                    SPUtils.getPreferences(activity).putLong(BaseConfig.UNI_ID, userBean.getUniId());
                    SPUtils.getPreferences(activity).putString(BaseConfig.UNI_NAME, userBean.getUniName());
                    SPUtils.getPreferences(activity).setToken(userBean.getToken());
                    SPUtils.getPreferences(activity).setTokenTime();
                    SPUtils.getPreferences(activity).putBoolean(BaseConfig.IS_AUTHEN, userBean.isAuth());
                    SPUtils.getPreferences(activity).putLong(BaseConfig.UNI_DATA_ID, userBean.getUniDataId());
                    SPUtils.getPreferences(activity).setLinkMainToken(userBean.getToken());
                    SPUtils.getPreferences(activity).putString(BaseConfig.USER_SIGN, userBean.getUserSign());

                    LiteOrmDBUtil.getLiteOrm(activity);
                }

                listener.onResult(status, msg, 0, null);
            }
        });
    }

}
